<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      websocket: null,
    }
  },
  created() {
    //页面刚进入时开启长连接
    this.initWebSocket()
  },
  destroyed: function () {
    //页面销毁时关闭长连接
    this.websocketclose();
  },
  methods: {
    initWebSocket() { //初始化weosocket
      const wsuri = "ws://localhost:8080/listen_new_notify"
      this.websocket = new WebSocket(wsuri);
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onclose = this.websocketclose;
    },

    websocketonopen() {
      console.log("WebSocket连接成功");
    },
    websocketonerror(e) { // 错误
      console.log("WebSocket连接发生错误");
    },
    websocketonmessage(e) { // 数据接收
      console.log('通知数据', JSON.parse(e.data));
      const time = new Date(+new Date(JSON.parse(e.data).time) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
      this.$notify({
        title: '您有一条新的通知！',
        message: '时间：' + time,
        position: 'top-right',
        duration: 0,
        type: 'warning',
        onClick() {
        }
      });

    },

    websocketsend(agentData) { //数据发送 
      this.websock.send(agentData);
    },

    websocketclose(e) { // 关闭 
      console.log("connection closed (" + e.code + ")");
    },
  }
}
</script>
